<?php
// +----------------------------------------------------------------------
// | Exchanges
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.bloveambition.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com>
// +----------------------------------------------------------------------

/**
 * 数据签名认证
 * 
 * @param array $data
 *            被认证的数据
 * @return string 签名
 * @author derek <693472824@qq.com>
 */
function data_auth_sign ($data) {
    // 数据类型检测
    if (! is_array($data)) {
        $data = (array) $data;
    }
    ksort($data); // 排序
    $code = http_build_query($data); // url编码并生成query字符串
    $sign = sha1($code . 'blovex4'); // 生成签名
    return $sign;
}

/**
 * 调用系统的API接口方法（静态方法）
 * api('Admin/getName','id=5'); 调用公共模块的User接口的getName方法
 * api('Admin/Admin/getName','id=5'); 调用Admin模块的Admin接口
 * 
 * @param string $name
 *            格式 [模块名]/接口名/方法名
 * @param array|string $vars
 *            参数
 * @author derek <693472824@qq.com>
 */
function api ($name, $vars = array()) {

    $array = explode('/', $name);
    $method = array_pop($array);
    $classname = array_pop($array);
    $module = $array ? array_pop($array) : 'Common';
    $callback = $module . '\\Api\\' . $classname . 'Api::' . $method;
    if (is_string($vars)) {
        parse_str($vars, $vars);
    }
    return call_user_func_array($callback, $vars);
}

/**
 * 系统非常规MD5加密方法
 * 
 * @param string $str
 *            要加密的字符串
 * @return string
 * @author derek <693472824@qq.com>
 */
function think_ucenter_md5 ($str, $key = 'Exchanges') {

    return '' === $str ? '' : md5(sha1($str) . $key);
}

/**
 * 从普通时间转换为Linux时间截
 *
 * @param string $dtime
 *            普通时间
 * @return string
 * @author derek <693472824@qq.com>
 */
function GetMkTime ($dtime) {

    if (! preg_match("/[^0-9]/", $dtime)) {
        return $dtime;
    }
    $dtime = trim($dtime);
    $dt = Array(
            1970,
            1,
            1,
            0,
            0,
            0
    );
    $dtime = preg_replace("/[\r\n\t]|日|秒/", " ", $dtime);
    $dtime = str_replace("年", "-", $dtime);
    $dtime = str_replace("月", "-", $dtime);
    $dtime = str_replace("时", ":", $dtime);
    $dtime = str_replace("分", ":", $dtime);
    $dtime = trim(preg_replace("/[ ]{1,}/", " ", $dtime));
    $ds = explode(" ", $dtime);
    $ymd = explode("-", $ds[0]);
    if (! isset($ymd[1])) {
        $ymd = explode(".", $ds[0]);
    }
    if (isset($ymd[0])) {
        $dt[0] = $ymd[0];
    }
    if (isset($ymd[1]))
        $dt[1] = $ymd[1];
    if (isset($ymd[2]))
        $dt[2] = $ymd[2];
    if (strlen($dt[0]) == 2)
        $dt[0] = '20' . $dt[0];
    if (isset($ds[1])) {
        $hms = explode(":", $ds[1]);
        if (isset($hms[0]))
            $dt[3] = $hms[0];
        if (isset($hms[1]))
            $dt[4] = $hms[1];
        if (isset($hms[2]))
            $dt[5] = $hms[2];
    }
    foreach ($dt as $k => $v) {
        $v = preg_replace("/^0{1,}/", '', trim($v));
        if ($v == '') {
            $dt[$k] = 0;
        }
    }
    $mt = mktime($dt[3], $dt[4], $dt[5], $dt[1], $dt[2], $dt[0]);
    if (! empty($mt)) {
        return $mt;
    } else {
        return time();
    }
}

/**
 * 返回格林威治标准时间
 *
 * @param string $format
 *            字符串格式
 * @param string $timest
 *            时间基准
 * @return string
 */
function MyDate ($format = 'Y-m-d H:i:s', $timest = 0) {

    if (empty($format)) {
        $format = 'Y-m-d H:i:s';
    }
    return empty($timest) ? '' : date($format, $timest);
}

/**
 * 减去时间
 *
 * @param int $ntime
 *            当前时间
 * @param int $ctime
 *            减少的时间
 * @return int
 */
function SubDay ($ntime, $ctime) {

    $dayst = 3600 * 24;
    $cday = ceil(($ntime - $ctime) / $dayst);
    return $cday;
}

/**
 * 增加天数
 *
 * @param int $ntime
 *            当前时间
 * @param int $aday
 *            增加天数
 * @return int
 */
function AddDay ($ntime, $aday) {

    $dayst = 3600 * 24;
    $oktime = $ntime + ($aday * $dayst);
    return $oktime;
}

/**
 * 返回格式化(Y-m-d H:i:s)的是时间
 *
 * @param int $mktime
 *            时间戳
 * @return string
 */
function GetDateTimeMk ($mktime) {

    return MyDate('Y-m-d H:i:s', $mktime);
}

/**
 * 返回格式化(Y-m-d)的日期
 *
 * @param int $mktime
 *            时间戳
 * @return string
 */
function GetDateMk ($mktime) {

    if ($mktime == "0")
        return "暂无";
    else
        return MyDate("Y-m-d", $mktime);
}

/**
 * 将时间转换为距离现在的精确时间
 *
 * @param int $seconds
 *            秒数
 * @return string
 */
function FloorTime ($seconds) {

    $times = '';
    $days = floor(($seconds / 86400) % 30);
    $hours = floor(($seconds / 3600) % 24);
    $minutes = floor(($seconds / 60) % 60);
    $seconds = floor($seconds % 60);
    if ($seconds >= 1)
        $times .= $seconds . '秒';
    if ($minutes >= 1)
        $times = $minutes . '分钟 ' . $times;
    if ($hours >= 1)
        $times = $hours . '小时 ' . $times;
    if ($days >= 1)
        $times = $days . '天';
    if ($days > 30)
        return false;
    $times .= '前';
    return str_replace(" ", '', $times);
}

/**
 * 格式化字节大小
 * 
 * @param number $size
 *            字节数
 * @param string $delimiter
 *            数字和单位分隔符
 * @return string 格式化后的带单位的大小
 * @author derek <693472824@qq.com>
 */
function format_bytes ($size, $delimiter = '') {

    $units = array(
            'B',
            'KB',
            'MB',
            'GB',
            'TB',
            'PB'
    );
    for ($i = 0; $size >= 1024 && $i < 5; $i ++)
        $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 计算时间差
 * 
 * @param integer $starttime
 *            开始时间
 * @param integer $endtime
 *            结束时间
 * @return string
 */
function GetTimeDiff ($starttime, $endtime) {

    $return = '';
    
    $endtime = empty($endtime) ? NOW_TIME : $endtime;
    
    if (empty($starttime)) {
        return $return;
    }
    
    $timediff = $endtime - $starttime;
    $days = intval($timediff / 86400);
    $remain = $timediff % 86400;
    $hours = intval($remain / 3600);
    $remain = $remain % 3600;
    $minutes = intval($remain / 60);
    $seconds = $remain % 60;
    
    $return .= empty($days) ? '' : $days . '天';
    $return .= empty($hours) ? '' : $hours . '小时';
    $return .= empty($minutes) ? '' : $minutes . '分';
    $return .= empty($seconds) ? '' : $seconds . '秒';
    
    return $return;
}

/**
 * 系统加密方法
 * 
 * @param string $data
 *            要加密的字符串
 * @param string $key
 *            加密密钥
 * @param int $expire
 *            过期时间 单位 秒
 * @return string
 * @author derek <693472824@qq.com>
 */
function think_encrypt ($data, $key = '', $expire = 0) {

    $key = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data = base64_encode($data);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = '';
    
    for ($i = 0; $i < $len; $i ++) {
        if ($x == $l)
            $x = 0;
        $char .= substr($key, $x, 1);
        $x ++;
    }
    
    $str = sprintf('%010d', $expire ? $expire + time() : 0);
    
    for ($i = 0; $i < $len; $i ++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) %
                 256);
    }
    return str_replace(array(
            '+',
            '/',
            '='
    ), array(
            '-',
            '_',
            ''
    ), base64_encode($str));
}

/**
 * 系统解密方法
 * 
 * @param string $data
 *            要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param string $key
 *            加密密钥
 * @return string
 * @author derek <693472824@qq.com>
 */
function think_decrypt ($data, $key = '') {

    $key = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data = str_replace(array(
            '-',
            '_'
    ), array(
            '+',
            '/'
    ), $data);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data = substr($data, 10);
    
    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = $str = '';
    
    for ($i = 0; $i < $len; $i ++) {
        if ($x == $l)
            $x = 0;
        $char .= substr($key, $x, 1);
        $x ++;
    }
    
    for ($i = 0; $i < $len; $i ++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr(
                    (ord(substr($data, $i, 1)) + 256) - ord(
                            substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

/**
 * 获取字典值对应的中文名称
 * 
 * @author derek <693472824@qq.com>
 */
function get_dictionary_enum_name ($dictGroupName, $enumID) {

    $dict = C($dictGroupName);

    $enumID = trim($enumID, ',');
    $list = explode(',', $enumID);
    
    $str = '';
    
    if($dict){
        
        foreach ($list as $key=>$val){
        
            if(is_array($dict['dict_enum']) && $dict['dict_enum'][$val]){
                
                $str .= empty($str) ? '' : ';';
                
                $str .= $dict['dict_enum'][$val]['enum_name'] ? $dict['dict_enum'][$val]['enum_name'] : '';
            }
        }
    }
    
    return $str;
}

/**
 * 获取字典枚举值列表
 * 
 * @param string $dictGroupName
 *            字典标识
 * @return mixed|multitype:
 * @author derek <693472824@qq.com>
 */
function get_dictionary_enum ($dictGroupName) {

    $dict = C($dictGroupName);
    
    if ($dict && is_array($dict['dict_enum'])) {
        
        return $dict['dict_enum'];
    } else {
        
        return array();
    }
}

/**
 * 获取系统配置项值
 */
function get_system_config ($configName) {

    $configValue = C($configName);
    
    if (! empty($configValue)) {
        
        return $configValue;
    } else {
        return '';
    }
}

/**
 * 随机字符
 * 
 * @param number $length
 *            长度
 * @param string $type
 *            类型
 * @param number $convert
 *            转换大小写
 * @return string
 */
function random ($length = 6, $type = 'string', $convert = 0) {

    $config = array(
            'number' => '1234567890',
            'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
            'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );
    
    if (! isset($config[$type]))
        $type = 'string';
    $string = $config[$type];
    
    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i ++) {
        $code .= $string{mt_rand(0, $strlen)};
    }
    if (! empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    return $code;
}


/**
 * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
 * 修复BUG：应该以文件名filename作为缓存key，而不是name
 * @param string $name 缓存名称
 * @param mixed $value 缓存值
 * @param string $path 缓存路径
 * @return mixed
 */
function F_M($name, $value='', $path=DATA_PATH) {
    static $_m_cache  =   array();
    $filename       =   $path . $name . '.php';
    if ('' !== $value) {
        if (is_null($value)) {
            // 删除缓存
            if(false !== strpos($name,'*')){
                return false; // TODO
            }else{
                unset($_m_cache[$filename]);
                return Think\Storage::unlink($filename,'F');
            }
        } else {
            Think\Storage::put($filename,serialize($value),'F');
            // 缓存数据
            $_m_cache[$filename]  =   $value;
            return null;
        }
    }
    
    // 获取缓存数据
    if (isset($_m_cache[$filename]))
        return $_m_cache[$filename];
    if (Think\Storage::has($filename,'F')){
        $value      =   unserialize(Think\Storage::read($filename,'F'));
        $_m_cache[$filename]  =   $value;
    } else {
        $value          =   false;
    }
    return $value;
}


/**
 * 验证手机号码格式
 *
 * @param string $mobile
 *            手机号
 * @return boolean 是否匹配
 */
function checkMobile ($mobile) {

    return preg_match("/^1[34578]\d{9}$/", $mobile);
}
?>